package demo03;

import demo02.entity.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class hw4_25 {

    /**
     * 自己尝试对，插入，修改，删除，查询方法做一下封装；
     * 提示，写一个类，比如UserDao,这个类中有四个方法
     * <p>
     * void insert(String userid,String password,String name);
     * void update(int userid,String userid,String password,String name);
     * void delete(int userid)
     * List select();
     * 写一个主函数，测试此类；
     */

    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    public hw4_25(Connection conn) {
        this.conn = conn;
    }

    //插入
    public void insert(int userid, String loginname, String userpwd, String realname) {
        String sql = "insert into t_users values(?,?,?,?)";
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, userid);
            ps.setString(2, loginname);
            ps.setString(3, userpwd);
            ps.setString(4, realname);
            ps.executeUpdate();
            System.out.println("添加成功");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeResources();
        }
    }

    //更新
    public void update(int userid, String loginname, String userpwd, String realname) {
        String sql = "update t_users set loginname=?,userpwd=?,realname=? where userid=?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, loginname);
            ps.setString(2, userpwd);
            ps.setString(3, realname);
            ps.setInt(4, userid);
            int rows = ps.executeUpdate();
            if (rows > 0) {
                System.out.println("更新成功");
            } else {
                System.out.println("更新失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeResources();
        }
    }

    //删除
    public void delete(int userid) {
        String sql = "delete from t_users where userid=?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, userid);
            int rows = ps.executeUpdate();
            if (rows > 0) {
                System.out.println("删除成功");
            } else {
                System.out.println("用户不存在");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeResources();
        }
    }

    //查询所有用户
    public List<User> select() {
        List<User> users = new ArrayList<>();
        String sql = "select * from t_users";
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                users.add(new User(
                        rs.getInt("userid"),
                        rs.getString("loginname"),
                        rs.getString("userpwd"),
                        rs.getString("realname")
                ));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeResources();
        }
        return users;
    }


    //登录
    private boolean login(String loginname, String userpwd) throws SQLException {
        String sql = "SELECT COUNT(*) FROM t_users WHERE loginname = ? AND userpwd = ?";
        try {
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, loginname);
            stmt.setString(2, userpwd);
            try (ResultSet rs = stmt.executeQuery()) {
                return rs.next() && rs.getInt(1) > 0;
            }
        }catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeResources();
        }
    }


    private void closeResources() {
        try {
            if (rs != null) rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (ps != null) ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class User {

        private int userid;
        private String loginname;
        private String userpwd;
        private String realname;

        public User(int userid, String loginname, String userpwd, String realname) {
            this.userid = userid;
            this.loginname = loginname;
            this.userpwd = userpwd;
            this.realname = realname;
        }

        @Override
        public String toString() {
            return "User{" +
                    "userid=" + userid +
                    ", loginname='" + loginname + '\'' +
                    ", userpwd='" + userpwd + '\'' +
                    ", realname='" + realname + '\'' +
                    '}';
        }
    }


    public static void main(String[] args) {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/homework4_24",
                    "root",
                    "1234"
            );

            hw4_25 h = new hw4_25(conn);
            /*
            1.添加两个用户,分别是
             liubei,liubei,‘刘备’；
             guanyu,guanyu,关宇；
             */
            h.insert(3, "liubei", "liubei", "刘备");
            h.insert(4, "guanyu", "guanyu", "关宇");

            /*
             * 2.修改；
             * 修改guanyu的密码，改成tiger;
             * 修改userid是2的用户，改成andy,tiger,‘安迪’；
             */
            h.update(4, "guanyu", "tiger", "关宇");
            h.update(2, "andy", "tiger", "安迪");

            /*
            3.删除
             * 删除userid是3的用户；
             */
            h.delete(3);


            /*
            4.查询
             * 查询出所有的用户，并将信息打印出来
             */
            h.select().forEach(System.out::println);

            /*
            5.登录
            要求用户输入用户名和密码，判断是否登录成功，如果成功，则显示所有的用户信息
            不成功，则提示"用户名或密码错误",使用Scanner来接收用户名和密码；
             */
            Scanner scanner = new Scanner(System.in);

            System.out.print("请输入用户名: ");
            String username1 = scanner.nextLine();
            System.out.print("请输入密码: ");
            String password1 = scanner.nextLine();

            if (h.login(username1, password1)) {
                System.out.println("登录成功！");
            } else {
                System.out.println("用户名或密码错误");
            }


        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
